package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */
@RestController
@RequestMapping("/setmeal")
@Slf4j
@Api(tags = "套餐相关接口")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishService dishService;
    @Autowired
    private CacheManager cacheManager;

    /**
     * 套餐分页查询
     */
    @GetMapping("/page")
    @ApiOperation(value = "套餐分页查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "页码",required = true),
            @ApiImplicitParam(name = "pageSize",value = "每页记录数",required = true),
            @ApiImplicitParam(name = "name",value = "套餐名称",required = false)
    })
    public R<Page> page(int page, int pageSize, String name) {
        //创建分页构造器对象
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        Page<SetmealDto> setmealDtoPage = new Page<>();

        //添加查询条件，根据name进行like模糊查询
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.like(name != null, Setmeal::getName, name);

        //添加排序条件，根据更新时间降序排列
        setmealLambdaQueryWrapper.orderByDesc(Setmeal::getUpdateTime);

        //执行查询
        setmealService.page(setmealPage, setmealLambdaQueryWrapper);

        //将setmealPage中除了records属性都拷贝到setmealDtoPage
        BeanUtils.copyProperties(setmealPage, setmealDtoPage, "records");

        //单独处理records
        List<Setmeal> records = setmealPage.getRecords();

        List<SetmealDto> list = records.stream().map((item -> {
            SetmealDto setmealDto = new SetmealDto();
            //将records中的属性拷贝给setmealDto,但是菜品分类名称要单独赋值覆盖
            BeanUtils.copyProperties(item, setmealDto);

            //获取每个菜品分类id
            Long categoryId = item.getCategoryId();

            //通过菜品分类id查询菜品分类名称
            Category category = categoryService.getById(categoryId);
            if (category != null) {//判断是否为null
                String categoryName = category.getName();

                //将查询到的菜品分类名称赋值给setmealDto
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        })).collect(Collectors.toList());

        setmealDtoPage.setRecords(list);
        return R.success(setmealDtoPage);
    }

    /**
     * 新增套餐，同时需要保存套餐和菜品的关联关系
     */
    @PostMapping
    @CacheEvict(value = "setmealGroup",allEntries = true)//setmealGroup名称下所有的缓存数据
    @ApiOperation(value = "新增套餐接口")
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        setmealService.saveWithDish(setmealDto);
        return R.success("新增套餐成功");
    }


    /**
     * 删除套餐
     */
    @DeleteMapping
    @CacheEvict(value = "setmealGroup",allEntries = true)//setmealGroup名称下所有的缓存数据
    @ApiOperation(value = "套餐删除接口")
    public R<String> delete(@RequestParam List<Long> ids){
        setmealService.removeWithDish(ids);
        return R.success("套餐删除成功");
    }


    /**
     * 根据套餐id查询套餐数据
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "套餐条件查询接口")
    public R<SetmealDto> getByIdWithDish(@PathVariable Long id){
        SetmealDto setmealDto = setmealService.getByIdWithDish(id);
        return R.success(setmealDto);
    }


    /**
     * 修改套餐，同时需要修改套餐和菜品的关联关系
     */
    @PutMapping
    @CacheEvict(value = "setmealGroup",allEntries = true)//setmealGroup名称下所有的缓存数据
    @ApiOperation(value = "修改套餐接口")
    public R<String> update(@RequestBody SetmealDto setmealDto) {
        setmealService.updateWithDish(setmealDto);
        return R.success("套餐修改成功");
    }


    /**
     * 起售/停售套餐
     */
    @PostMapping("/status/{status}")
    @CacheEvict(value = "setmealGroup",allEntries = true)//setmealGroup名称下所有的缓存数据
    @ApiOperation(value = "起售/停售套餐接口")
    public R<String> updateStatus(@PathVariable int status,@RequestParam List<Long> ids){
        LambdaUpdateWrapper<Setmeal> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(Setmeal::getId,ids);
        updateWrapper.set(Setmeal::getStatus,status);
        setmealService.update(updateWrapper);
        return R.success("操作成功");
    }



    /**
     * 移动端根据条件查询套餐数据
     */
    @GetMapping("list")
    @Cacheable(value = "setmealGroup",key = "#setmeal.categoryId+''+#setmeal.status",unless = "#result==null")
    @ApiOperation(value = "移动端根据条件查询套餐数据接口")
    public R<List<Setmeal>> list(Setmeal setmeal){
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Setmeal::getCategoryId,setmeal.getCategoryId());
        List<Setmeal> list = setmealService.list(queryWrapper);
        return R.success(list);
    }
}
